<template>
  <div class="trainers-list">
    <el-card shadow="never" style="margin-bottom: 20px; border: none">
      <div class="header-search">
        <el-form :inline="true" :model="searchField">
          <el-form-item label="姓名">
            <el-input
              v-model="searchField.username"
              placeholder="根据姓名搜索"
              clearable
              class="search-ipt"
              @clear="handleSearch"
            />
          </el-form-item>
          <el-form-item label="电话">
            <el-input
              v-model="searchField.phone"
              placeholder="根据电话搜索"
              clearable
              class="search-ipt"
              @clear="handleSearch"
            />
          </el-form-item>
          <el-form-item label="部门">
            <el-cascader
              v-model="currentDepart"
              :options="departmentOptions"
              :props="{ checkStrictly: true, multiple: true }"
              @change="handleCascaderChange"
              @remove-tag="handleRemoveTag"
            />
          </el-form-item>
          <el-form-item label="">
            <div class="search-warp">
              <el-button
                type="primary"
                icon="el-icon-search"
                @click="handleSearch"
              >搜索</el-button>
              <el-button type="danger" @click="resetSearchInfo">重置</el-button>
            </div>
          </el-form-item>
        </el-form>
      </div>
    </el-card>

    <el-card shadow="never" style="border: none">
      <el-table
        v-loading="loading"
        :data="trainingList"
        style="width: 100%"
        border
        stripe
      >
        <el-table-column prop="username" label="姓名" align="center" />
        <el-table-column prop="username" label="部门" align="center">
          <template v-slot="{ row }">
            {{ getFieldData(row.fieldData, 'department_id')?.valueType?.name }}
            <!--            {{ row.userCompany?.department?.name || "-" }}-->
          </template>
        </el-table-column>
        <el-table-column prop="gender" label="性别" align="center">
          <template v-slot="{ row }">
            <el-tag>
              {{ row.gender === 1 ? "男" : row.gender === 0 ? "女" : "不详" }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="course" label="课程" align="center">
          <template v-slot="{ row }">
            <el-button
              type="text"
              @click="handleShowCourseList(row)"
            >点击查看</el-button>
          </template>
        </el-table-column>
        <el-table-column prop="phone" label="联系电话" align="center" />
        <el-table-column label="操作" align="center">
          <template v-slot="{ row }">
            <div>
              <el-tooltip
                :enterable="false"
                class="item"
                effect="dark"
                content="添加课程"
                placement="top"
              >
                <el-button
                  circle
                  type="primary"
                  icon="el-icon-plus"
                  @click="handleAddCourse(row)"
                />
              </el-tooltip>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <div class="page-ination">
        <Pagination
          style="margin-top: 0; padding-bottom: 0"
          :total="pageInfo.total"
          :limit="pageInfo.paginate"
          @pagination="handlePagination"
        />
      </div>
    </el-card>

    <DialogContent
      :close-on-click-modal="false"
      :visible.sync="showCourseList"
      :title="dialogTitle"
      width="800px"
      @closed="closedCourseDialog"
    >
      <div class="course-list-warp" style="height: 60vh; overflow: auto;">
        <div v-if="courseList.length > 0">
          <el-table
            v-loading="userCourseLoading"
            :data="courseList"
            style="width: 100%"
            border
            stripe
          >
            <el-table-column prop="title" label="课程名称" align="center" />
            <el-table-column
              prop="created_at"
              label="创建时间"
              align="center"
            />
            <el-table-column label="操作" align="center">
              <template v-slot="{ row }">
                <el-button
                  type="text"
                  style="color: #F56C6C;"
                  @click="deleteUserCourse(row)"
                >
                  删除
                </el-button>

                <el-button type="text" @click="toCourseDetails(row)">课程详情</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <el-empty v-else description="暂无课程..." />
      </div>
    </DialogContent>
    <el-dialog
      :visible.sync="dialogVisible"
      title="添加课程"
      :close-on-click-modal="false"
      width="50%"
      @close="addCourseToUserDialogClose"
    >
      <el-table
        ref="addCourseToUserTableRef"
        v-loading="userCourseLoading"
        style="width: 100%"
        :data="course"
        :row-key="getRowKey"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" :reserve-selection="true" />
        <el-table-column label="封面" align="center">
          <template v-slot="{ row }">
            <el-image class="courseAvatar" :src="row.cover">
              <div slot="error">
                <div class="image-slot">暂无图片</div>
              </div>
            </el-image>
          </template>
        </el-table-column>
        <el-table-column prop="title" label="标题" align="center" />
        <el-table-column prop="day" label="完成天数" align="center" />
      </el-table>
      <Pagination
        :total="page.total"
        :limit="page.paginate"
        :page="page.page"
        @pagination="pagination"
      />
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addCourse">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getAllUser } from '@/api/v2/personnel'
import { getDept } from '@/api/basic'
import Pagination from '@/components/Pagination'
import DialogContent from '@/components/DialogContent/index.vue'
import { course, addUserCourse } from '@/api/train'
import {
  getCourseList,
  addCourseToUser,
  getCourseListByUserSelected,
  deleteCourseToUser,
  getCourseListNoSelected
} from '@/api/v2/course'
import { value } from '@/utils/kris_utils'
export default {
  name: '',
  components: {
    Pagination,
    DialogContent
  },
  data() {
    return {
      userCourseLoading: false,
      showCourseList: false,
      courseList: [],
      dialogTitle: '',
      loading: false,
      trainingList: [],
      dialogVisible: false,
      pageInfo: {
        paginate: 10,
        total: 0,
        page: 1
      },
      page: {
        paginate: 10,
        total: 0,
        page: 1
      },
      course: [],
      currentItem: [],
      userId: '',
      searchField: {
        title: '',
        username: '',
        phone: '',
        department_id: null
      },
      currentDepart: null,
      departmentOptions: [],
      currentUser: null
    }
  },
  created() {
    this.init()
    // this.showCourse()
  },
  methods: {
    getRowKey(row) {
      return row.id
    },
    async init() {
      const result = await Promise.allSettled([
        this.getTrainingList(),
        this.getDepartmentList()
      ])
      console.log('result ------>', result)
    },
    async getTrainingList() {
      this.loading = true
      try {
        const res = await getAllUser(this.paramsFormat())
        const { data, meta } = res
        this.trainingList = data
        this.pageInfo.total = meta.total
        console.log('res ------>', res)
      } catch (error) {
        this.$message.error('获取培训人员失败')
        console.log('error ------>', error)
      } finally {
        this.loading = false
      }
    },

    getFieldData(fieldData, field) {
      const findField = () => {
        for (const item of fieldData) {
          console.log('123 --------->', 123)
          if (item.field.field === field) {
            return item
          }
        }
      }

      return findField()
    },
    async getDepartmentList() {
      try {
        const res = await getDept()
        this.departmentOptions = this.formatDepartmentsOptions(res.data)
      } catch (error) {
        console.log('error ------>', error)
      }
    },
    formatDepartmentsOptions(depart) {
      return depart.reduce((pre, cur) => {
        if (!cur.children || cur.children.length <= 0) {
          pre.push({ value: cur.id, label: cur.name })
        } else {
          const item = { value: cur.id, label: cur.name, children: [] }
          const child = this.formatDepartmentsOptions(cur.children)
          item.children.push(...child)
          pre.push(item)
        }
        return pre
      }, [])
    },
    paramsFormat() {
      const { paginate, page } = this.pageInfo
      return {
        paginate,
        page,
        ...this.searchField,
        department_id: this.searchField.department_id
          ? JSON.stringify(this.searchField.department_id)
          : null
      }
    },
    handlePagination(e) {
      this.pageInfo.paginate = e.limit
      this.pageInfo.page = e.page
      this.getTrainingList()
      console.log('e ------>', e)
    },
    pagination(e) {
      this.page.page = e.page
      this.page.paginate = e.limit
      this.showCourse(this.currentUser)
    },
    handleSearch() {
      this.pageInfo.page = 1
      this.getTrainingList()
    },
    resetSearchInfo() {
      this.pageInfo = this.$options.data().pageInfo
      this.searchField = this.$options.data().searchField
      this.currentDepart = null
      this.getTrainingList()
    },
    handleCascaderChange(e) {
      console.log('e ------>', e)
      const list = []
      e.forEach((item) => {
        list.push(item[item.length - 1])
      })
      this.searchField.department_id = list.length > 0 ? list : null
    },
    handleShowCourseList(row) {
      console.log('row ------>', row)
      this.showCourseList = true
      this.currentUser = row.id
      console.log(row.course)
      this.getUserCourseList(row.id)
      this.dialogTitle = `${row.username}-课程列表`
    },

    async getUserCourseList(id) {
      this.userCourseLoading = true
      try {
        const res = await getCourseListByUserSelected({ user_id: id })
        this.courseList = res.data
      } catch (error) {
        this.$message.error(error.response.data.message || '用户课程获取失败')
      } finally {
        setTimeout(() => {
          this.userCourseLoading = false
        }, 500)
      }
    },

    closedCourseDialog() {
      this.courseList = []
      this.dialogTitle = ''
    },
    async showCourse(id) {
      this.userCourseLoading = true
      try {
        const params = {
          paginate: this.page.paginate,
          page: this.page.page,
          user_id: id
        }
        const res = await getCourseListNoSelected(params)
        this.course = res?.data
        this.page.total = res?.meta?.total
      } catch (error) {
        this.$message.error(error?.response?.data?.message || '课程列表获取失败')
      } finally {
        setTimeout(() => {
          this.userCourseLoading = false
        }, 500)
      }
    },
    // 多选
    handleSelectionChange(e) {
      this.currentItem = e.map((item) => item.id)
      console.log(JSON.stringify(this.currentItem), 1111)
    },
    async addCourse() {
      try {
        const ids = JSON.stringify(this.currentItem)
        console.log(ids)
        const params = {
          user_id: this.userId,
          course_id: ids
        }

        await addCourseToUser(params).catch((err) => {
          throw new Error(value(err, 'response.data.message', '添加课程失败'))
        })

        // await this.showCourse().catch((err) => {
        //   throw new Error(value(err, 'response.data.message', '添加课程失败'))
        // })

        this.dialogVisible = false
        this.currentItem = []
        this.$message({
          message: '添加课程成功',
          type: 'success'
        })
        this.getTrainingList()
      } catch (e) {
        this.dialogVisible = false
        this.$message.error(e.message)
      }
    },
    handleAddCourse(row) {
      console.log('row ------>', row)
      this.dialogVisible = true
      this.userId = row.id
      this.course = []
      this.currentUser = row.id
      this.showCourse(row.id)
    },
    detail(row) {
      console.log('row ------>', row)
      this.$router.push({
        path: '/train/list',
        query: {
          id: row.id,
          tag_title: '详情'
        }
      })
    },
    handleRemoveTag(e) {
      console.log('e handleRemoveTag------>', e)
      this.searchField.department_id = this.searchField.department_id.filter(
        (item) => item !== e[e.length - 1]
      )
      this.searchField.department_id =
        this.searchField.department_id.length > 0
          ? this.searchField.department_id
          : null
      console.log(
        'this.searchField.department_id ------>',
        this.searchField.department_id
      )
      this.handleSearch()
    },
    async getUserNoCourse(id) {
      try {
        const { data } = await getCourseListNoSelected({ user_id: id })
        this.course = data
      } catch (error) {
        this.$message.error('获取用户课程失败')
        console.log(error, 'error')
      }
    },
    deleteUserCourse(row) {
      this.$confirm(
        '是否移除该课程？',
        '提示',
        {
          type: 'warning',
          confirmButtonText: '确定',
          cancelButtonText: '取消'
        }
      ).then(() => {
        const params = {
          user_id: this.currentUser,
          ids: JSON.stringify([row.id])
        }
        this.deleteUserCourseApi(params)
      })
    },

    async deleteUserCourseApi(params) {
      try {
        const res = await deleteCourseToUser(params)
        this.$message.success('删除成功')
        await this.getUserCourseList(params.user_id)
      } catch (error) {
        this.$message.error(error?.response?.data?.message || '删除失败')
      }
    },

    toCourseDetails(row) {
      this.$router.push({
        path: `/train/detail/${row.id}`
      })
    },

    addCourseToUserDialogClose() {
      console.log('12123 addCourseToUserDialogClose--------->', 12123)
      this.$refs.addCourseToUserTableRef.clearSelection()
      this.page.page = 1
    }
  }
}

</script>

<style scoped lang='scss'>
.header-search{
  .el-form-item{
    margin-bottom: 0px;
  }
}
.trainers-list {
  padding: 20px;
  .search-box{
    //margin-bottom: 20px;
    .search-warp {
      display: flex;
      align-items: center;
      padding: 10px;
      .title {
        color: #8e8e8e;
        margin-right: 10px;
      }
    }
  }
  .course-list-warp {
    min-height: 200px;
    max-height: 300px;
  }
  .courseAvatar {
    width: 60px;
    height: 60px;
  }
  .image-slot {
    width: 60px;
    height: 60px;
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 14px;
    background: #f5f7fa;
    color: #c0c4cc;
  }
}
</style>
